{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/steps.css' %}">
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <style>
        .has-input-error, .has-select-error {
            border: 1px solid #a94442;
        }

        .error-text, .td-input-error {
            color: #a94442;
        }

        #server_items tr>td>input, #server_items tr>td>select {
            width: 100%;
            height: 32px;
        }

        #server_items tr>td>textarea {
            width: 100%;
            height: 64px;
        }

    </style>
{% endblock %}

{% block content %}
    <form class="form-horizontal" id="server_form" style="min-width: 500px;">
        <div class="box box-primary" id="server_items">
            <div class="box-body">
                <input name="asset_type" id="asset_type" style="display: none;" value="server">
                <input type="text" style="display: none" name="asset_admin" id="asset_admin" value="{{ asset_admin.id }}">
                <div class="form-group">
                    <label for="server_type" class="col-sm-2 control-label">服务器类型</label>
                    <div class="col-sm-6">
                        <select class="form-control" id="server_type" name="server_type"
                                style="width: 100%;" onchange="deviceType()" >
                            <option value="0">物理机</option>
                            <option value="1" selected>虚拟机</option>
                        </select>
                    </div>
                </div>
                <div class="form-group hosted_on">
                    <label for="hosted_on" class="col-sm-2 control-label">宿主机</label>
                    <div class="col-sm-10">
                        <select class="form-control" id="hosted_on" name="hosted_on" style="width:100%;">
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label for="asset_applicant" class="col-sm-2 control-label">申请人<span class="text-red">*</span></label>
                    <div class="col-sm-6">
                        <input id="asset_applicant" class="form-control" name="asset_applicant"/>
                    </div>
                </div>
                <div class="form-group">
                    <label for="asset_runner" class="col-sm-2 control-label">负责人<span class="text-red">*</span></label>
                    <div class="col-sm-6">
                        <input id="asset_runner" class="form-control" name="asset_runner"/>
                    </div>
                </div>

                <div class="form-group">
                    <label for="asset_product" class="col-sm-2 control-label">产品名称</label>
                    <div class="col-sm-6">
                        <select style="display: none;" name="asset_product" id="asset_product">
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label for="IP_segment" class="col-sm-2 control-label">IP网段<span class="text-red">*</span></label>
                    <div class="col-sm-6">
                        <select name="IP_segment" id="IP_segment" style="display: none;"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label for="IP_state" class="col-sm-2 control-label">IP状态<span class="text-red">*</span></label>
                    <div class="col-sm-6">
                        <select style="display: none;" name="IP_state" id="IP_state">
                            <option value="0">空闲</option>
                            <option value="1">占用</option>
                            <option value="2">全部</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label for="server-setting" class="col-sm-2 control-label">服务器配置</label>
                    <div class="col-sm-9">
                        <div class="box box-widget">
                            <div class="box-header no-border" style="margin-bottom: -10px;">
                                <button type="button" class="btn btn-sm" id="add-server" data-toggle="tooltip" data-placement="top" data-original-title="新增服务器"><i class="glyphicon glyphicon-plus"></i></button>
                            </div>
                            <div class="box-body">
                                <table class="table table-hover table-responsive no-padding" id="settings-table" style="min-width: 800px;width: 100%;">
                                    <thead>
                                        <tr>
                                            <th></th>
                                            <th>项目编号/项目名称<span class="text-red">*</span></th>
                                            <th>备注</th>
                                            <th>IP地址<span class="text-red">*</span></th>
                                            <th>设备环境</th>
                                            <th>使用期限</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <button type="button" class="btn btn-xs" onclick="removeRow(this);"><i class="glyphicon glyphicon-minus"></i></button>
                                            </td>
                                            <td><input name="asset_nu"/></td>
                                            <td><textarea name="asset_memo"></textarea></td>
                                            <td>
                                                <select name="IP" class="IP" style="display: none;">
                                                </select>
                                            </td>
                                            <td>
                                                <select class="form-control" name="asset_environment">
                                                    {% for environment in asset_environment_ %}
                                                        <option value="{{ environment.0 }}">{{ environment.1 }}</option>
                                                    {% endfor %}
                                                </select>
                                            </td>
                                            <td>
                                                <select class="form-control" name="asset_time">
                                                    <option value="0">短期</option>
                                                    <option value="1" selected>长期</option>
                                                </select>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="box-footer">
                <button type="button" class="btn btn-default pull-right" onclick="history.go(-1)">返回</button>
                <button type="button" class="btn btn-info pull-right" onclick="addStep1();">确认添加，并返回资产列表</button>
            </div>
        </div>
    </form>
{% endblock %}

{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <!-- DataTables -->
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script>
        $(function () {
            $('.select2').select2();

            $('#asset_product').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                placeholder: '请输入搜索条件',
                load: function(query, callback) {
                    $.ajax({
                        url: '/project/find_product_name/',
                        data: {
                            product_name: query
                        },
                        dataType: 'json',
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });

            $('#IP_segment').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                onChange: function(){
                    var ipSegment = $('#IP_segment').val()
                    var ipstate = $('#IP_state').val()
                    $('select.IP').each(function (i,ele) {
                        var IPSelect = ele.selectize
                        ipDetailSelect(ipSegment,ipstate,IPSelect)
                    })
                }
            });

            var IPSegmentSelect = $('#IP_segment')[0].selectize;
            $.ajax({
                type: 'POST',
                url: '/assets/find_ip_segment/'
            }).then(function (data) {
                IPSegmentSelect.addOption(data.results)
            });

            $('#IP_state').selectize({
                onChange: function(){
                    var ipSegment = $('#IP_segment').val()
                    var ipstate = $('#IP_state').val()
                    $('select.IP').each(function (i,ele) {
                        var IPSelect = ele.selectize
                        ipDetailSelect(ipSegment,ipstate,IPSelect)
                    })
                }
            })

            $('.IP').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
            });

            function ipDetailSelect(ipSegment,ipstate,IPSelect){
                IPSelect.clear()
                IPSelect.clearOptions()
                if(!ipSegment){
                    return
                }
                $.ajax({
                    type: 'POST',
                    url: '/assets/find_ip/',
                    data: {IP_segment: ipSegment, IP_state: ipstate},
                }).then(function (data) {
                    IPSelect.addOption(data.results)
                });
            }

            $('#hosted_on').select2({
                allowClear: true,
                ajax: {
                    url: '/assets/find_hosted_on',
                    dataType: 'json',
                    data: function (params) {
                        params.offset = 6
                        params.page = params.page || 1
                        var query = {
                            search: params.term,
                            page: params.page,
                            offset: params.offset,
                        }
                        return query;
                    },
                    processResults: function (data, params) {
                        var page = params.page || 1
                        return {
                            results: data.results,
                            pagination: {
                                more: (page*params.offset) < data.total_count
                            }
                        };
                    },
                    cache: true
                  },
                minimumInputLength: 2,
                templateResult: formatRepo,
                templateSelection: formatRepoSelection,
                placeholder: '查询IP地址 或 项目编号/名称'
            });

            function formatRepo (repo) {
                if (repo.loading) {
                    return repo.text;
                }
                var $container = $("<div class='select2-result-repository clearfix'>" +
                      "<div class='select2-result-repository-element'>" + repo.text +
                    "</div></div>");
                return $container;
            }

            function formatRepoSelection (repo) {
                return repo.text;
            }

            var table1 = $('#settings-table').DataTable({
                paging: false,
                searching: false,
                info: false,
            })

            $("#add-server").click(function () {
                var n = $("select.IP").length+1
                table1.row.add(['<button type="button" class="btn btn-xs" onclick="removeRow(this);"><i class="glyphicon glyphicon-minus"></i></button>',
                    '<input name="asset_nu"/>',
                    '<textarea name="asset_memo"></textarea>',
                    '<td><select name="IP" class="IP" id="IP'+n+'" style="display: none;"></select></td>',
                    '<select class="form-control" name="asset_environment">\n' +
                    '{% for environment in asset_environment_ %}\n'+
                    '<option value="{{ environment.0 }}">{{ environment.1 }}</option>\n'
                    +'{% endfor %}\n' +
                    '</select>',
                    '<select class="form-control" name="asset_time">\n' +
                    '<option value="0">短期</option>\n' +
                    '<option value="1" selected>长期</option>\n' +
                    '</select>']).draw()
                $('#IP'+n).selectize({
                    valueField: 'id',
                    labelField: 'text',
                    searchField: 'text',
                });
                var IPSelect = $('#IP'+n)[0].selectize
                var ipSegment = $('#IP_segment').val()
                var ipstate = $('#IP_state').val()
                ipDetailSelect(ipSegment,ipstate,IPSelect)
            })
        });

        function removeRow(ele){
            var table = $('#settings-table').DataTable()
            var count = table.rows().count()
            if(count != 1){
                var row_obj = $(ele).parent().parent()
                table.row(row_obj).remove().draw()
            }
        }

        function addStep1(){
            var asset_applicant_obj = $('#asset_applicant')
            var asset_runner_obj = $('#asset_runner')
            var asset_product_obj = $('#asset_product')
            var IP_segment_obj = $('#IP_segment')
            var asset_applicant = asset_applicant_obj.val().trim()
            var asset_runner = asset_runner_obj.val().trim()
            var asset_product = $('#asset_product').val()
            var IP_segment = $('#IP_segment').val()
            $('.has-error').removeClass('has-error')
            $('.error-text').remove()
            $('.td-input-error').remove()
            $(".selectize-input").removeClass('has-select-error').parent().parent().parent().find('span').remove()
            if(asset_applicant.length == 0){
                asset_applicant_obj.after('<span class="error-text">该字段不能为空</span>')
                asset_applicant_obj.parent().addClass('has-error')
            } else if(asset_applicant.length > 20){
                asset_applicant_obj.after('<span class="error-text">该字段不能超过20个字符</span>')
                asset_applicant_obj.parent().addClass('has-error')
            }
            if(asset_runner.length == 0){
                asset_runner_obj.after('<span class="error-text">该字段不能为空</span>')
                asset_runner_obj.parent().addClass('has-error')
            } else if( asset_runner.length > 20){
                asset_runner_obj.after('<span class="error-text">该字段不能超过20个字符</span>')
                asset_runner_obj.parent().addClass('has-error')
            }
            if(IP_segment.length == 0){
                IP_segment_obj.parent().append('<span class="help-block">该字段不能为空</span>').find('.selectize-input').addClass('has-select-error')
                IP_segment_obj.parent().addClass('has-error')
            }
            $('#settings-table tbody>tr').each(function(index, value){
                $(value).find('td').each(function(index, value){
                    var cell = $(value)
                    var ele = cell.find('input, textarea, select')
                    ele.removeClass('has-input-error')
                    if(index == 1){
                        var asset_nu = ele.val().trim()
                        if(asset_nu.length == 0){
                            cell.append('<span class="error-text">该字段不能为空</span>')
                            cell.find('input').addClass('has-input-error')
                        } else if(asset_nu.length > 100){
                            cell.append('<span class="error-text">该字段不能超过100个字符</span>')
                            cell.find('input').addClass('has-input-error')
                        }
                    }
                })
            })
            $('select.IP.selectized').each(function(index, value){
                if($(value).val() === ""){
                    $(value).parent().append('<span class="td-input-error">该字段不能为空</span>').find('.selectize-input').addClass('has-select-error')
                }
            })

            if($('.has-error, .error-text, .td-input-error, .has-select-error').length > 0){return}

            var formList = $("#server_form").serializeArray()
            var assetObj = {}
            var basicInfo = {}
            var asset_nuList = []
            var asset_memoList = []
            var IPList = []
            var asset_environmentList = []
            var asset_timeList = []
            var resultList = []
            $(formList).each(function(index, value){
                if(["asset_type","server_type","asset_applicant","asset_runner","asset_product","IP_segment","IP_state","asset_admin","hosted_on"].includes(value.name)){
                    if (value.name.indexOf('asset_') !== -1) {
                        assetObj[value.name] = value.value;
                    } else {
                        basicInfo[value.name] = value.value
                    }
                }
                if(["asset_nu","asset_memo","IP","asset_environment","asset_time"].includes(value.name)){
                    eval(value.name+'List').push(value.value)
                }
            })
            var maxLength = Math.max(asset_nuList.length,asset_memoList.length,IPList.length,asset_environmentList.length,asset_timeList.length)
            for(var i=0;i<maxLength;i++){
                var tmp = {...basicInfo}
                tmp['assets'] = assetObj;
                tmp.assets.asset_nu = asset_nuList[i]
                tmp.assets.asset_memo = asset_memoList[i]
                tmp.IP = IPList[i]
                tmp.assets.asset_environment = asset_environmentList[i]
                tmp.assets.asset_management_ip = IPList[i]
                var nowDate = new Date()
                tmp.assets.asset_purchase_day = nowDate.getFullYear()+"-"+(nowDate.getMonth()+1)+"-"+nowDate.getDate()
                var expireDate = null
                asset_timeList[i] === "1"? expireDate = new Date(nowDate.setFullYear(nowDate.getFullYear()+70)):expireDate = new Date(nowDate.setMonth(nowDate.getMonth()+3))
                tmp.assets.asset_expire_day = expireDate.getFullYear()+"-"+(expireDate.getMonth()+1)+"-"+expireDate.getDate()
                resultList.push($.extend(true, {}, tmp))
            }
            var successNum = 0
            $(resultList).each(function(){
                $.ajax({
                    url: '/api/server_assets/',
                    type: 'POST',
                    async: false,
                    data: JSON.stringify(this),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function () {
                        successNum += 1
                    }
                })
            })
            if(maxLength>successNum){
                $.confirm({
                    title: 'Tips',
                    content: '成功添加'+successNum+'条记录,失败添加'+(maxLength-successNum)+'条记录！',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            window.location.href = '{% url 'assets_list' %}';
                        },
                    }
                })
            } else {
                $.confirm({
                    title: 'Tips',
                    content: '成功添加'+successNum+'条记录！',
                    type: 'green',
                    buttons: {
                        Ok: function () {
                            window.location.href = '{% url 'assets_list' %}';
                        },
                    }
                })
            }
        }

        function deviceType() {
            let hosted_obj = $('.hosted_on');
            let device_type = $('#server_type').val();
            if(device_type === '1'){
                hosted_obj.show()
            } else {
                $('#hosted_on').val('').trigger('change'),hosted_obj.hide()
            }
        }
    </script>
{% endblock %}